package cn.jinjimi.app.managers;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.DateUtils;
import cn.jinjimi.base.util.GsonUtils;
import cn.jinjimi.base.util.MD5Utils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.entity.ActivityInfo;
import cn.jinjimi.app.modules.notify.LocalReceiver;
import cn.jinjimi.app.store.helper.NoticeDbHelper;
import cn.jinjimi.app.bean.SharePrefKeys;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Roy
 * 首页活动信息本地推送管理类
 * Date: 16/10/12
 */
public class LocalPushActInfoManager {

    /**
     * 缓存activityInfoList的key
     *
     * @param activityInfos
     */
    public static void setActivityListsCache(Context context, List<ActivityInfo> activityInfos) {
        if (activityInfos != null && !activityInfos.isEmpty()) {

            clearActivityInfoCache(context);

            String[] keys = new String[activityInfos.size()];
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < activityInfos.size(); i++) {
                keys[i] = MD5Utils.MD5(activityInfos.get(i).link);
                buffer.append(keys[i]).append(",");
            }

            PreferenceManager.setData(SharePrefKeys.PREF_ACTIVITYINFO_CACHE_KEY, buffer.toString());
        }
    }

    /**
     * 网络请求放回后，缓存完整ActivityInfo信息并设置闹钟
     *
     * @param context
     * @param activityInfo
     */
    public static void saveAndPushActivityInfo(Context context, ActivityInfo activityInfo) {
        // 获取缓存的key
        String keyCache = PreferenceManager.getStringData(SharePrefKeys.PREF_ACTIVITYINFO_CACHE_KEY);
        if (StringUtils.isEmpty(keyCache))
            return;
        String[] keys = keyCache.split(",");

        String targetKey = MD5Utils.MD5(activityInfo.link);

        if (activityInfo != null) {
            PreferenceManager.setData(targetKey, GsonUtils.toJson(activityInfo));

            // 设置与闹钟对应的红点提醒
            NoticeDbHelper.setActivityAlertNotice(activityInfo);

            for (int i = 0; i < keys.length; i++) {
                int quesCode = 10 * (i + 1);
                if (keys[i].equals(targetKey)) {
                    for (ActivityInfo.Alert alert : activityInfo.data.alerts) {
                        PushAlert(context, alert, activityInfo.data.getAlertState(), quesCode);
                        quesCode++;
                    }
                }
            }
        }
    }

    /**
     * 获取缓存的ActivityInfoList对象
     *
     * @return
     */
    private static List<ActivityInfo> getActivityInfoCache() {
        // 获取缓存的key
        String keyCache = PreferenceManager.getStringData(SharePrefKeys.PREF_ACTIVITYINFO_CACHE_KEY);
        if (StringUtils.isEmpty(keyCache))
            return null;
        String[] keys = keyCache.split(",");

        List<ActivityInfo> activityInfos = new ArrayList<>();
        for (String key : keys) {
            if (StringUtils.isNotEmpty(key)) {
                String value = PreferenceManager.getStringData(key);
                ActivityInfo activityInfo = GsonUtils.fromJson(value, ActivityInfo.class);
                if (activityInfo != null) {
                    activityInfos.add(activityInfo);
                }
            }
        }
        return activityInfos;
    }

    /**
     * 清除本地ActivityInfo缓存对象
     * 清除前先取消所有已有的闹钟
     *
     * @param context
     */
    public static void clearActivityInfoCache(Context context) {
        PushAllCancle(context);

        String keyCache = PreferenceManager.getStringData(SharePrefKeys.PREF_ACTIVITYINFO_CACHE_KEY);
        if (StringUtils.isEmpty(keyCache))
            return;

        String[] keys = keyCache.split(",");
        for (String key : keys) {
            PreferenceManager.removeData(key);
        }
        PreferenceManager.removeData(SharePrefKeys.PREF_ACTIVITYINFO_CACHE_KEY);

    }

    /**
     * 根据缓存定制所有闹钟
     *
     * @param context
     */
    public static void PushAllSet(Context context) {

        List<ActivityInfo> activityInfos = getActivityInfoCache();
        if (activityInfos == null || activityInfos.isEmpty())
            return;

        for (int i = 0; i < activityInfos.size(); i++) {
            ActivityInfo activityInfo = activityInfos.get(i);

            // 设置与闹钟对应的红点提醒
            NoticeDbHelper.setActivityAlertNotice(activityInfo);

            int quesCode = 10 * (i + 1);

            if (activityInfo.data == null || activityInfo.data.alerts == null)
                continue;

            for (ActivityInfo.Alert alert : activityInfo.data.alerts) {
                PushAlert(context, alert, activityInfo.data.getAlertState(), quesCode);
                quesCode++;
            }
        }
    }

    /**
     * 取消所有本地闹钟
     *
     * @param context
     */
    private static void PushAllCancle(Context context) {
        List<ActivityInfo> activityInfos = getActivityInfoCache();
        if (activityInfos == null || activityInfos.isEmpty())
            return;

        for (int i = 0; i < activityInfos.size(); i++) {
            ActivityInfo activityInfo = activityInfos.get(i);
            int quesCode = 10 * (i + 1);

            if (activityInfo.data == null || activityInfo.data.alerts == null)
                continue;

            for (ActivityInfo.Alert alert : activityInfo.data.alerts) {
                Intent intent = new Intent(context, LocalReceiver.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, quesCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
                alarmManager.cancel(pendingIntent);

                quesCode++;
            }
        }

    }

    /**
     * 针对每一个需要推送的闹钟设置
     *
     * @param context
     * @param alert
     * @param alertState
     * @param quesCode
     */
    private static void PushAlert(Context context, ActivityInfo.Alert alert, boolean alertState, int quesCode) {
        Intent intent = new Intent(context, LocalReceiver.class);
        intent.putExtra(BundleKey.TITLE, alert.title);
        intent.putExtra(BundleKey.CONTENT, alert.content);
        intent.putExtra(BundleKey.URL, alert.url);
        intent.putExtra(BundleKey.CODE, quesCode);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, quesCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (alertState) {

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());

            Date date = DateUtils.ParseHHmmssString(alert.time);
            if (date != null) {

                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(date);
                calendar1.add(Calendar.MINUTE, -1);// 提前一分钟进行提醒

                calendar.set(Calendar.HOUR_OF_DAY, calendar1.get(Calendar.HOUR_OF_DAY));
                calendar.set(Calendar.MINUTE, calendar1.get(Calendar.MINUTE));
                calendar.set(Calendar.SECOND, calendar1.get(Calendar.SECOND));

                if (calendar.getTimeInMillis() < System.currentTimeMillis())
                    calendar.add(Calendar.DAY_OF_MONTH, 1);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            }
        } else {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
        }
    }
}
